from apps import jsonrpc_v1
from .models import db, GoodsCategory, GoodsSPU


@jsonrpc_v1.method("Goods.goods_category")
def goods_category():
	"""商品分类"""
	cat_list = GoodsCategory.query.filter(
		GoodsCategory.is_show == True,
		GoodsCategory.is_deleted == False
	).order_by(
		GoodsCategory.sort.asc(),
		GoodsCategory.id.desc()
	).limit(6).all()

	data = []

	for category in cat_list:
		data.append(category.__to_dict__(["id", "name"]))

	return data


@jsonrpc_v1.method("Goods.home_goods")
def home_goods():
	"""首页每日"心"品推荐商品"""
	goods_list = GoodsSPU.query.filter(
		GoodsSPU.is_recommend == True,
		GoodsSPU.is_show == True,
		GoodsSPU.is_deleted == False
	).order_by(
		GoodsSPU.sort.asc(),
		GoodsSPU.id.desc()
	).limit(5).all()

	data = []
	for goods in goods_list:
		data.append(goods.__to_dict__(["id", "title", "image_url"]))

	return data


@jsonrpc_v1.method("Goods.list_goods(category=Number, page=Number, size=Number)")
def list_goods(category=0, page=1, size=5):
	"""列表页商品列表"""
	data = {}
	try:
		query = GoodsSPU.query.filter(
			GoodsSPU.is_show == True,
			GoodsSPU.is_deleted == False
		)

		# 分类ID作为条件查询
		if category > 0:
			query = query.filter(GoodsSPU.category_id == category)

		paginate = query.order_by(
			GoodsSPU.sort.asc(),
			GoodsSPU.id.desc()
		).paginate(page, per_page)
		# 当前分页页码
		data["page"] = paginate.page
		# 上一页页码
		data["prev_num"] = paginate.prev_num
		# 下一页页码
		data["next_num"] = paginate.next_num
		# 是否有上一页
		data["has_prev"] = paginate.has_prev
		# 是否有下一页
		data["has_next"] = paginate.has_next
		# 总页码
		data["pages"] = paginate.pages
		# 总数据量
		data["total"] = paginate.total
		# 当前页数据项
		data["items"] = []
		for goods in paginate.items:
			data['items'].append(goods.__to_dict__(["id", "title", "image_url"]))

	except:
		data = {}

	return data